package cn.swing.ushare.user.webapi.service;


import cn.swing.ushare.pojo.vo.UserLoginVO;
import cn.swing.ushare.user.webapi.mapper.LoginMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    LoginMapper mapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        System.out.println("即将取数据库找信息");
        UserLoginVO admin = mapper.getLoginInfoByUsername(username);
        System.out.println("admin=" + admin);
        if (admin == null) {
            throw new BadCredentialsException("登录失败用户名不存在");
        }
        System.out.println("查询到匹配的管理员数据，需要将此数据转换为UserDetails并返回");
        UserDetails userDetails = User.builder()
                .username(admin.getUsername())
                .password(admin.getPassword())
                .accountExpired(false)
                .accountLocked(false)
                .disabled(admin.getIsEnable() != 1)
                .credentialsExpired(false)
                .authorities(admin.getPermissions().toArray(new String[]{}))
                .build();
        System.out.println("转换得到UserDetails=" + userDetails);
        mapper.updateLastLoginTime(admin.getUsername());
        return userDetails;


    }
}
